package com.syl.springcloud.authorization.service;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import static com.syl.springcloud.authorization.constant.LoginConstant.DB_PASSWORD;

/**
 * 定制 登录密码比对行为
 * @author syl
 * @create 2018-08-08 10:42
 **/
public class CustomAuthenticationProvider extends DaoAuthenticationProvider {

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            logger.debug("Authentication failed: no credentials provided");

            throw new BadCredentialsException(messages.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.badCredentials",
                    "Bad credentials"));
        }

        String userDetailsPassword = userDetails.getPassword();
        String presentedPassword = authentication.getCredentials().toString();
        // 如果是从数据中取出的密码则直接比对
        if(!StringUtils.isBlank(presentedPassword) && presentedPassword.indexOf(DB_PASSWORD) > -1){
            presentedPassword = presentedPassword.replace(DB_PASSWORD,"");
            if(!userDetailsPassword.equals(presentedPassword)){
                throw new BadCredentialsException(messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.badCredentials",
                        "Bad credentials"));
            }
        }
        else if (!getPasswordEncoder().matches(presentedPassword, userDetailsPassword)) {
            logger.debug("Authentication failed: password does not match stored value");

            throw new BadCredentialsException(messages.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.badCredentials",
                    "Bad credentials"));
        }
    }
}
